package com.waijiaojun.tpo.service;

import com.waijiaojun.tpo.entity.GoodsOrder;
import com.waijiaojun.tpo.entity.Tpo;
import com.waijiaojun.tpo.entity.weixin.WeixinTwoDimensionalCode;
import com.waijiaojun.tpo.entity.weixin.WeixinUserInfo;
import com.waijiaojun.tpo.repository.GoodsOrderDao;
import com.waijiaojun.tpo.repository.TpoDao;
import com.waijiaojun.tpo.repository.UserAnswersDao;
import com.waijiaojun.tpo.repository.weixin.WeixinTwoDimensionalCodeDao;
import com.waijiaojun.tpo.repository.weixin.WeixinUserInfoDao;
import com.waijiaojun.tpo.utils.Constants;
import com.waijiaojun.tpo.utils.DateUtil;
import com.waijiaojun.tpo.utils.Util;
import com.waijiaojun.tpo.vo.IndexData;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class UserService {

    @Resource
    private GoodsOrderDao goodsOrderDao;

    @Resource
    private UserAnswersDao userAnswersDao;

    @Resource
    private WeixinUserInfoDao weixinUserInfoDao;

    @Resource
    private WeixinTwoDimensionalCodeDao weixinTwoDimensionalCodeDao;

    public IndexData getIndexData(String openid){
        IndexData indexData = userAnswersDao.getDurationSumByOpenid(openid);
        if(indexData==null){
            indexData = new IndexData();
        }
        if(indexData.getStudyDuration()==null){
            indexData.setStudyDuration(0L);
        }
        if(indexData.getQuestionNumber()==null){
            indexData.setQuestionNumber(0);
        }

        GoodsOrder goodsOrder = goodsOrderDao.getPayOrderByOpenid(openid);
        if(goodsOrder!=null){
            indexData.setStudyDays(DateUtil.getDays(goodsOrder.getCreateDate()));
        }else{
            indexData.setStudyDays(1);
        }

        // 学习的词汇量：做个练习题的文章包含的词汇
        Integer number  = userAnswersDao.studyVocabularyNumber(openid);
        indexData.setQuantityOfVocabulary(number);

        WeixinUserInfo weixinUserInfo = weixinUserInfoDao.getByOpenIdAndWeixinPublicId(openid, Constants.publicId);
        indexData.setNickname(weixinUserInfo.getNicknameForBase64Decoder());
        indexData.setHeadimgurl(weixinUserInfo.getHeadimgurl());
        return indexData;
    }

    public String getQRUrl(String openid) {
        WeixinTwoDimensionalCode code = weixinTwoDimensionalCodeDao.getByOpenId(openid);
        if(code!=null){
            return Util.toFullOssUrl(code.getImageUrl());
        }else{
            // 返回公众号的二维码
            return "http://file.waijiaojun.com/tpo/production/DD3FBDA0-4253-4b98-B489-E01CE278B587.png";
        }
    }
}
